import { Component, Vue, Watch } from 'vue-property-decorator' // @ is an alias to /src
// import style from './UserInfo.less'
import { State, Action } from 'vuex-class'
import { RootState } from '@/store'
import { ElForm } from 'element-ui/types/form'
import styles from './MobileUpdate.less'
import { Route } from 'vue-router'
Component.registerHooks(['beforeRouteLeave'])

const formRule = {
  mobile: [
    { required: true, message: '请输入新手机号', trigger: ['blur', 'change'] },
    {
      pattern: /^1[0-9]{10}$/,
      message: '手机号格式不正确',
      trigger: ['blur', 'change'],
    },
  ],
  code: [
    {
      required: true,
      message: '请输入手机验证码',
      trigger: ['blur', 'change'],
    },
    { len: 6, message: '长度不正确', trigger: ['blur', 'change'] },
  ],
}

@Component({})
export default class MobileUpdate extends Vue {
  private active: number = 0

  private oldMobileData: any = {
    mobile: '',
    code: '',
  }
  private newMobileData: any = {
    mobile: '',
    code: '',
  }
  private loading = false
  private timer: any = null
  private countDownTime: number = 0
  private gotoLigonTimer: number = 0
  private sendDisabled: boolean = false

  @State((state: RootState) => state.user.accountMobile)
  private accountMobile!: string

  @Action('user/info') private userInfo!: any
  @Action('user/sendMobileCode') private sendMobileCode!: any
  @Action('user/modifyMobileVerify') private modifyMobileVerify!: any
  @Action('user/sendRebindingMsg') private sendRebindingMsg!: any
  @Action('user/rebindTheMobile') private rebindTheMobile!: any
  protected render() {
    return (
      <div class={styles.mobileUpdate}>
        <div>
          <el-steps active={this.active} align-center>
            <el-step title="填写认证信息" />
            <el-step title="绑定新手机号" />
            <el-step title="完成" />
          </el-steps>
          <el-form
            v-show={this.active === 0}
            size="mini"
            ref="form1"
            {...{
              props: { model: this.oldMobileData, rules: formRule },
            }}
          >
            <el-form-item label="手机号">
              <el-input v-model={this.accountMobile} disabled />
            </el-form-item>
            <el-form-item prop="code" class="code-item" label="验证码">
              <el-input
                class="input-code"
                v-model={this.oldMobileData.code}
                placeholder="请输入手机验证码"
                autocomplete="off"
              />
              <el-button
                class={styles.mobileCode}
                onClick={this.getMobileCode}
                disabled={!!this.countDownTime || this.sendDisabled}
              >
                {this.countDownTime ? `${this.countDownTime}s` : '发送验证码'}
              </el-button>
            </el-form-item>
          </el-form>
          <el-form
            v-show={this.active === 1}
            size="mini"
            ref="form2"
            {...{
              props: { model: this.newMobileData, rules: formRule },
            }}
          >
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model={this.newMobileData.mobile}
                placeholder="请输入新的手机号码"
              />
            </el-form-item>
            <el-form-item prop="code" class="code-item" label="验证码">
              <el-input
                class="input-code"
                v-model={this.newMobileData.code}
                placeholder="请输入手机验证码"
                autocomplete="off"
              />
              <el-button
                class={styles.mobileCode}
                onClick={this.sendCode}
                disabled={!!this.countDownTime || this.sendDisabled}
              >
                {this.countDownTime ? `${this.countDownTime}s` : '发送验证码'}
              </el-button>
            </el-form-item>
          </el-form>
          {this.active !== 3 && (
            <div class="footer">
              <el-button
                type="primary"
                disabled={this.nextDisabled}
                loading={this.loading}
                onClick={() => this.next()}
              >
                下一步
              </el-button>
              {this.active === 1 && (
                <span class="tips">
                  <i class="el-icon-info" />
                  账户如已绑定浙政钉，重置手机号后将会需要重新绑定
                </span>
              )}
            </div>
          )}
          {this.active === 3 && (
            <div class="success-view">
              <i class="el-icon-circle-check" />
              <h1>更换成功</h1>
              <p>恭喜您已完成手机号变更</p>
              <el-button class="link-btn" onClick={() => this.gotoLogin()}>
                重新登录{this.countDownTime && `（${this.countDownTime}s）`}
              </el-button>
            </div>
          )}
        </div>
      </div>
    )
  }

  @Watch('accountMobile')
  private mobileChange(val: string) {
    this.oldMobileData.mobile = val
  }

  @Watch('active')
  private activeChange(val: number) {
    this.countDownTime = 0
    this.timer && clearInterval(this.timer)
    if (val === 3) {
      this.countDown(5, (time: number) => {
        this.countDownTime = time
        if (time === 0) {
          this.$router.push({ name: 'homepage', query: { login: 'true' } })
        }
      })
    }
  }

  private getMobileCode() {
    this.sendDisabled = true

    this.sendMobileCode()
      .then((res: any) => {
        this.sendDisabled = false

        if (!this.countDownTime) {
          // 倒计时 90s
          this.countDown(90, (time: number) => {
            this.countDownTime = time
          })
        }
      })
      .catch((e: any) => {
        this.sendDisabled = false
      })
  }

  private countDown(times: number, step?: any, cb?: any) {
    let time = times
    if (step) step(time)
    this.timer && clearInterval(this.timer)
    this.timer = setInterval(() => {
      if (time <= 0) {
        this.timer && clearInterval(this.timer)
        if (cb) cb()

        return
      }

      time--
      if (step) step(time)
    }, 1000)
  }

  private sendCode() {
    ;(this.$refs['form2'] as ElForm).validateField('mobile', (val: string) => {
      if (!val) {
        this.sendDisabled = true
        this.sendRebindingMsg({
          newMobile: this.newMobileData.mobile,
        })
          .then((res: any) => {
            this.sendDisabled = false

            if (!this.countDownTime) {
              // 倒计时 90s
              this.countDown(90, (time: number) => {
                this.countDownTime = time
              })
            }
          })
          .catch((e: any) => {
            this.sendDisabled = false
          })
      }
    })
  }

  private next() {
    if (this.active === 0) {
      ;(this.$refs['form1'] as ElForm).validate((val: boolean) => {
        if (val) {
          this.loading = true
          this.modifyMobileVerify({ mobileCode: this.oldMobileData.code })
            .then((res: any) => {
              this.loading = false
              this.active++
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    } else if (this.active === 1) {
      ;(this.$refs['form2'] as ElForm).validate((val: boolean) => {
        if (val) {
          this.loading = true
          this.rebindTheMobile({
            newMobile: this.newMobileData.mobile,
            mobileCode: this.newMobileData.code,
          })
            .then((res: any) => {
              this.loading = false
              this.active = 3
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
  private gotoLogin() {
    this.$router.push({ name: 'homepage', query: { login: 'true' } })
  }

  get nextDisabled() {
    return (
      (this.active === 0 && !this.oldMobileData.code) ||
      (this.active === 1 &&
        (!this.newMobileData.code || !this.newMobileData.mobile))
    )
  }

  beforeRouteLeave(to: Route, from: Route, next: any) {
    this.timer && clearInterval(this.timer)
    next()
  }
}
